import React, {useCallback, useMemo} from 'react'
import {isActiveAllToggle, isActiveToggle, ToggleControlDataType} from './utils'
import {Button} from '../button/Button'

interface ToggleControlProps {
  dataList: ToggleControlDataType[]

  value: string[]
  onChange: (value: string[]) => void
  isMultiple?: boolean
  isAllToggle?: boolean
  isDisabled?: boolean

  className?: string
}

const ToggleControl: React.FC<ToggleControlProps> = ({
  dataList,
  value,
  onChange,
  isDisabled,
  isMultiple,
  isAllToggle,
  className,
}): React.ReactElement => {
  const onToggle = useCallback(
    (data: ToggleControlDataType, index: number, checked: boolean) => {
      if (isMultiple) {
        let newValues: string[] = [...(value as string[])]
        if (checked) {
          newValues.push(data.value)
        } else {
          newValues.splice(
            newValues.findIndex((item) => item === data.value),
            1,
          )
        }
        onChange(newValues)
      } else {
        onChange(checked ? [data.value] : [])
      }
    },
    [isMultiple, onChange, value],
  )

  const onToggleAll = useCallback(() => {
    onChange([])
  }, [onChange])

  const renderList: React.ReactElement = useMemo(() => {
    return (
      <>
        {isAllToggle && (
          <Button
            key={'all'}
            style={'text'}
            size={'xs'}
            className={'mr-x4 mb-x2'}
            hover={'light'}
            disabled={isDisabled}
            isActive={isActiveAllToggle(value)}
            onClick={() => {
              onToggleAll()
            }}>
            Все
          </Button>
        )}
        {dataList.map((data, index) => (
          <Button
            key={data.value}
            style={'text'}
            size={'xs'}
            className={'mr-x4 mb-x2'}
            title={data.title || undefined}
            hover={'light'}
            disabled={isDisabled}
            isActive={isActiveToggle(data, value)}
            onClick={() => {
              onToggle(data, index, !isActiveToggle(data, value))
            }}>
            {data.label}
          </Button>
        ))}
      </>
    )
  }, [dataList, isAllToggle, isDisabled, onToggle, onToggleAll, value])

  const renderContent: React.ReactElement = useMemo(() => {
    return <div className={'toggle-control ' + (className ? className : '')}>{renderList}</div>
  }, [className, renderList])

  return <>{renderContent}</>
}

export {ToggleControl}
